package com.acwing.partition12;

import java.io.*;
import java.util.ArrayDeque;
import java.util.Arrays;

/**
 * @author `RKC`
 * @date 2022/1/22 14:53
 */
public class AC1169糖果 {

    private static final int N = (int) (1e5 + 10), M = 3 * N, INF = 0x3f3f3f3f;
    private static int[] head = new int[N], element = new int[M], next = new int[M], weight = new int[M];
    private static int[] dist = new int[N], cnt = new int[N];
    private static boolean[] inQueue = new boolean[N];
    private static int n = 0, idx = 0;
    //玄学优化，使用栈来代替队列，在一些情况下能更快的找到环
    private static ArrayDeque<Integer> queue = new ArrayDeque<>(N);

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        String[] s = reader.readLine().split("\\s+");
        n = Integer.parseInt(s[0]);
        int k = Integer.parseInt(s[1]);
        Arrays.fill(head, -1);
        while (k-- > 0) {
            s = reader.readLine().split("\\s+");
            int t = Integer.parseInt(s[0]), u = Integer.parseInt(s[1]), v = Integer.parseInt(s[2]);
            if (t == 1) {
                createEdge(u, v, 0);
                createEdge(v, u, 0);
            } else if (t == 2) createEdge(u, v, 1);
            else if (t == 3) createEdge(v, u, 0);
            else if (t == 4) createEdge(v, u, 1);
            else createEdge(u, v, 0);
        }
        //超级源点到每个点连一条边，因为每个同学至少都要一颗糖果，所以 xi>=x0+1
        for (int i = 1; i <= n; i++) createEdge(0, i, 1);
        //如果有正环，说明无解
        if (spfa()) writer.write(-1 + "\n");
        else {
            long ans = 0;
            for (int i = 1; i <= n; i++) ans += dist[i];
            writer.write(ans + "\n");
        }
        writer.flush();
    }

    private static boolean spfa() {
        for (int i = 0; i <= n; i++) dist[i] = -INF;
        dist[0] = 0;
        queue.addLast(0);
        inQueue[0] = true;
        while (!queue.isEmpty()) {
            int u = queue.pollLast();
            inQueue[u] = false;
            for (int i = head[u]; i != -1; i = next[i]) {
                int v = element[i];
                if (dist[v] < dist[u] + weight[i]) {
                    dist[v] = dist[u] + weight[i];
                    cnt[v] = cnt[u] + 1;
                    if (cnt[v] >= n + 1) return true;
                    if (inQueue[v]) continue;
                    queue.addLast(v);
                    inQueue[v] = true;
                }
            }
        }
        return false;
    }

    private static void createEdge(int u, int v, int w) {
        element[idx] = v;
        next[idx] = head[u];
        head[u] = idx;
        weight[idx++] = w;
    }
}
